<?php

require_once 'propel/engine/builder/om/php5/PHP5MapBuilderBuilder.php';

/*
 * This file is part of the symfony package.
 * (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 * @package    symfony
 * @subpackage addon
 * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
 * @version    SVN: $Id: SfMapBuilderBuilder.php 3058 2006-12-16 17:17:26Z fabien $
 */
class KeMapBuilderBuilder extends PHP5MapBuilderBuilder
{
  public function build()
  {
    if (!DataModelBuilder::getBuildProperty('builderAddComments'))
    {
      return sfToolkit::stripComments(parent::build());
    }
    
    return parent::build();
  }

    public function getSequenceName($table)
    {
        $nombrePk="";
        foreach ($table->getPrimaryKey() as $pk)
        {
            $nombrePk=$pk->getName();
        }
        
        $result = null;
        if ($table->getIdMethod() == "native") 
        {
            $idMethodParams = $table->getIdMethodParameters();
            if ($idMethodParams === null) 
            {
                $result = $table->getName();
                if(strpos($result, ".") !== false)
                {
                    $result = str_replace(".", ".seq_", $result);
                }else
                {
                    $result = "seq_".$table->getName();
                }
                
                    
                $maxIdentifierLength = $this->getDatabase()->getPlatform()->getMaxColumnNameLength();
                /*if(strlen( $result) > $maxIdentifierLength)
                {
            
                    $result = substr($result, 0,  ($maxIdentifierLength-1));
                }*/
                
            } else 
            {
                $result = $idMethodParams[0]->getValue();
            }
        }
        return $result;
    }
	
  protected function addIncludes(&$script)
  {
    if (!DataModelBuilder::getBuildProperty('builderAddIncludes'))
    {
      return;
    }

    parent::addIncludes($script);
  }
  
  	protected function addClassBody(&$script)
	{
		$this->addConstants($script);
		$this->addAttributes($script);

		$this->addIsBuilt($script);
		$this->addGetDatabaseMap($script);
		$this->addDoBuild($script);
	}
	

  /*protected function addDoBuild(&$script)
  {
    parent::addDoBuild($script);

    // fix http://propel.phpdb.org/trac/ticket/235: Column sizes not being inserted into [table]MapBuilder->DoBuild() by PHP5MapBuilderBuilder
    $sizes = array();
    foreach ($this->getTable()->getColumns() as $col)
    {
      $sizes[$col->getPhpName()] = !$col->getSize() ? 'null' : $col->getSize();
    }
    $script = preg_replace("/\\\$tMap\->addColumn\('([^']+)', '([^']+)', '([^']+)', CreoleTypes\:\:VARCHAR, (false|true)\)/e", '"\\\$tMap->addColumn(\'$1\', \'$2\', \'$3\', CreoleTypes::VARCHAR, $4, {$sizes[\'$2\']})"', $script);
  }*/
  
	protected function addDoBuild(&$script)
	{

		$table = $this->getTable();
		$platform = $this->getPlatform();

		$script .= "
	/**
	 * The doBuild() method builds the DatabaseMap
	 *
	 * @return     void
	 * @throws     PropelException
	 */
	public function doBuild()
	{
		\$this->dbMap = Propel::getDatabaseMap(".$this->getPeerClassname()."::DATABASE_NAME);

		\$tMap = \$this->dbMap->addTable(".$this->getPeerClassname()."::TABLE_NAME);
		\$tMap->setPhpName('".$table->getPhpName()."');
		\$tMap->setClassname('" . $this->getObjectClassname() . "');
";
		if ($table->getIdMethod() == "native") {
			$script .= "
		\$tMap->setUseIdGenerator(true);
";
		} else {
			$script .= "
		\$tMap->setUseIdGenerator(false);
";
		}

		if ($table->getIdMethodParameters()) {
			$params = $table->getIdMethodParameters();
			$imp = $params[0];
			$script .= "
		\$tMap->setPrimaryKeyMethodInfo('".$imp->getValue()."');
";
		} elseif ($table->getIdMethod() == "native" && ($platform->getNativeIdMethod() == Platform::SEQUENCE)) {
			$script .= "
		\$tMap->setPrimaryKeyMethodInfo('".$this->getSequenceName($table)."');
";
		} elseif ($table->getIdMethod() == "native" && ($platform->getNativeIdMethod() == Platform::SERIAL)) {
			$script .= "
		\$tMap->setPrimaryKeyMethodInfo('".$this->getSequenceName($table)."');
";
		}

		// Add columns to map
		foreach ($table->getColumns() as $col) {
			$cfc=$col->getPhpName();
			$cup=strtoupper($col->getName());
			if (!$col->getSize()) {
				$size = "null";
			} else {
				$size = $col->getSize();
			}
			if ($col->isPrimaryKey()) 
            {
				if ($col->isForeignKey()) 
                {
					foreach ($col->getForeignKeys() as $fk) 
                    {
						$script .= "
		\$tMap->addForeignPrimaryKey('$cup', '$cfc', '".$col->getType()."' , '".$fk->getForeignTableName()."', '".strtoupper($fk->getMappedForeignColumn($col->getName()))."', ".($col->isNotNull() ? 'true' : 'false').", ".$size.");
";
					}
				} else 
                {
					$script .= "
		\$tMap->addPrimaryKey('$cup', '$cfc', '".$col->getType()."', ".var_export($col->isNotNull(), true).", ".$size.");
";
				}
			} else 
            {
				if ($col->isForeignKey()) 
                {
					foreach ($col->getForeignKeys() as $fk) 
                    {
						$script .= "
		\$tMap->addForeignKey('$cup', '$cfc', '".$col->getType()."', '".$fk->getForeignTableName()."', '".strtoupper($fk->getMappedForeignColumn($col->getName()))."', ".($col->isNotNull() ? 'true' : 'false').", ".$size.");
";
					}
			} else 
            {
					$script .= "
		\$tMap->addColumn('$cup', '$cfc', '".$col->getType()."', ".var_export($col->isNotNull(), true).", ".$size.");
";
             }
           } // if col-is prim key
		} // foreach
		
    	foreach($table->getUnices() as $uni)
	   {
	        $cols = $uni->getColumns();
	        $table = $uni->getTable();
	        if(count($cols)>1)
	        {
	            $uni = strtoupper(implode(",", $cols));
                foreach($cols as $c)
                {
                    $col = $table->getColumn($c);
			        $cup = strtoupper($col->getName());
                    $script .= "
		\$tMap->addValidator('$cup', 'unique_".$cup."', 'KeUniqueValidator', '$uni', 'Ya existe un elemento con el mismo nombre.');
";
                }
            }else
            {
                $col = $table->getColumn($cols[0]);
			    $cup = strtoupper($col->getName());
                $script .= "
		\$tMap->addValidator('$cup', 'unique_".$cup."', 'UniqueValidator', '', 'Ya existe un elemento con el mismo nombre.');
";
            }
       }
       
	// Add columns to map
		foreach ($table->getColumns() as $col) 
        {
			$cfc=$col->getPhpName();
			$cup=strtoupper($col->getName());
			if (!$col->getSize()) 
            {
				$size = "null";
			} else 
            {
				$size = $col->getSize();
			}


           if($size > 0 && $col->getType() == 'VARCHAR')
           {
$script .= "
        \$tMap->addValidator('$cup', 'maxLength_".$cup."', 'MaxLengthValidator', $size, 'El valor tiene demasiados caracteres. [max= $size]');
    ";
            }
            
  
            if($col->isNotNull() /*&& $col->getType() != 'INTEGER'*/)
           {
$script .= "
        \$tMap->addValidator('$cup', 'required_".$cup."', 'RequiredValidator', '', 'Este campo es necesario');
    ";
            } 
	} 
		

		foreach ($table->getValidators() as $val) {
			$col = $val->getColumn();
			$cup = strtoupper($col->getName());
			foreach ($val->getRules() as $rule) {
				if ($val->getTranslate() !== Validator::TRANSLATE_NONE) {
					$script .= "
		\$tMap->addValidator('$cup', '".$rule->getName()."', '".$rule->getClass()."', '".str_replace("'", "\'", $rule->getValue())."', ".$val->getTranslate()."('".str_replace("'", "\'", $rule->getMessage())."'));
";
				} else {
					$script .= "
		\$tMap->addValidator('$cup', '".$rule->getName()."', '".$rule->getClass()."', '".str_replace("'", "\'", $rule->getValue())."', '".str_replace("'", "\'", $rule->getMessage())."');
";
				} // if ($rule->getTranslation() ...
  			} // foreach rule
		}  // foreach validator

		$script .= "
	} // doBuild()
";

	}

  


} // PHP5ExtensionPeerBuilder

